package com.glink.manage.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.glink.common.contants.BaseConstants;
import com.glink.common.exception.GeneralSimpleException;
import com.glink.common.util.BaseCommonUtils;
import com.glink.manage.vo.user.UserBaseInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : qiushaoshan
 * @create 2025/1/7 18:23
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    
    @Override
    public void insertFill(MetaObject metaObject) {
        String userId = getCurrentUserId();
       
        Date date = new Date();
        if(StringUtils.isNotBlank(userId)){
            this.setFieldValByName("createUser", userId, metaObject);
            this.setFieldValByName("createUserId", userId, metaObject);
            String userName = findNameByUserId(userId);
            if(StringUtils.isNotBlank(userName)){
                this.setFieldValByName("createUserName", userName, metaObject);
                this.setFieldValByName("createUserFullName", userName, metaObject);
            }
        }
        
        this.setFieldValByName("createTime", date, metaObject);
        this.setFieldValByName("updateTime", date, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String userId = getCurrentUserId();
        Date date = new Date();
        if(StringUtils.isNotBlank(userId)){
            this.setFieldValByName("updateUser", userId, metaObject);
            this.setFieldValByName("updateUserId", userId, metaObject);
            String userName = findNameByUserId(userId);
            if(StringUtils.isNotBlank(userName)){
                this.setFieldValByName("updateUserName", userName, metaObject);
            }
        }
     
        this.setFieldValByName("updateTime", date, metaObject);
        this.setFieldValByName("modifyTime", date, metaObject);
    }

    private String getCurrentUserId(){
        String userId = "";
        try {
            userId = BaseCommonUtils.extractUserIdtByToken();
        } catch (GeneralSimpleException e) {
            throw new RuntimeException(e);
        }
        return userId;
    }

    public String findNameByUserId(String userId) {
        String userName = "";

        if(StringUtils.isBlank(userId)){
            return userName;
        }

        UserBaseInfoVO userVO = null;
        try {
            userVO = findRedisUserByPid(userId);
        }catch (Exception e){
            Object redisUserInfoObj = redisTemplate.opsForValue().get(BaseConstants.REDIS_USER_PREFIX + userId);
            log.error("获取redis用户信息异常:userId：{}, redisUserInfo:{}, exception:{}",userId, redisUserInfoObj, e.getMessage());
            if(redisUserInfoObj instanceof JSONObject){
                JSONObject jsonObject = (JSONObject) redisUserInfoObj;
                Object fullName = jsonObject.get("fullName");
                if(Objects.nonNull(fullName)){
                    log.error("获取redis用户信息:fullName：{}",fullName);
                    return (String) fullName;
                }
            }
        }
        if(Objects.nonNull(userVO) && Objects.nonNull(userVO.getId()) && Objects.nonNull(userVO.getFullName())){
            return userVO.getFullName();
        }

        try {
            userName = BaseCommonUtils.extractUserNameByToken();
        } catch (GeneralSimpleException e) {
            e.printStackTrace();
            log.error("token获取用户名称失败");
        }

        return userName;
    }

    public UserBaseInfoVO findRedisUserByPid(String personId){
        String redisUserInfo = redisTemplate.opsForValue().get(BaseConstants.REDIS_USER_PREFIX + personId);
        return JSON.parseObject(redisUserInfo, UserBaseInfoVO.class);
    }
}
